/*
 * @lc app=leetcode.cn id=16 lang=javascript
 *
 * [16] 最接近的三数之和
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function (nums, target) {
  nums.sort((a, b) => a - b);
  let min = Infinity;
  let help = function (left, i, right) {
    return nums[left] + nums[i] + nums[right];
  };
  let map = new Map();
  function abs(a, b) {
    return Math.abs(a - b);
  }
  for (let i = 1; i < nums.length - 1; i++) {
    let left = i - 1;
    let right = i + 1;
    while (left >= 0 && right <= nums.length - 1) {
      let sum = help(left, i, right);
      min = Math.min(abs(sum, target), min);
      if (!map.has(min)) {
        map.set(min, sum);
      }
      if (sum < target) {
        right++;
        
        
      } else if (sum > target) {
        left--;
       
      } else {
        return sum;
      }
    }
  }
  return map.get(min);
};
// @lc code=end
console.log(threeSumClosest([-1, 0, 1, 1, 55], 3));
